package control;

import ibatis.Account;
import ibatis.AccountDAOIbatis;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AcFrontController extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		execute(req,resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		execute(req,resp);

	}

	private void execute(HttpServletRequest req, HttpServletResponse resp) {
		String uri=req.getRequestURI();
		System.out.println("uri="+uri);
		
		String contextPath=req.getContextPath();
		System.out.println("contextPath="+contextPath);
		
		String command = uri.substring(contextPath.length());
		System.out.println("command="+command);
		
		try {
			
			req.setAttribute("login", "login/LoginForm.jsp");
			req.setAttribute("side", "/template/side.jsp");
			req.setAttribute("body", "studyContent.jsp");
			
			if(command.equals("/accountForm.ac")) {
				req.setAttribute("body", "account/accountForm.jsp");
				req.getRequestDispatcher("home.jsp").forward(req, resp);
			}
			else if(command.equals("/accountFormProc.ac")) {
				Account account = new Account();
				account.setId(Integer.parseInt(req.getParameter("id")));
				account.setFirstName(req.getParameter("firstName"));
				account.setLastName(req.getParameter("lastName"));
				account.setEmailAddress(req.getParameter("emailAddress"));
				
				AccountDAOIbatis.insertAccount(account);
				resp.sendRedirect("accountList.ac");
				
			} else if(command.equals("/accountList.ac")) {
				ArrayList<Account> list = 
						(ArrayList<Account>) AccountDAOIbatis.selectAllAccounts();
				req.setAttribute("list", list);
				req.setAttribute("body", "account/accountList.jsp");
				req.getRequestDispatcher("home.jsp").forward(req, resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 	
	}
}
